package cn.zl.GB28181.transmit.event.request.impl.message.notify.cmd;

import cn.yunbamboos.bean.ThreadPoolDynamicTaskExecutor;
import cn.zl.GB28181.core.RemoteAddressInfo;
import cn.zl.GB28181.storage.IDeviceStorage;
import cn.zl.GB28181.transmit.event.request.BaseSIPRequestProcessor;
import cn.zl.GB28181.transmit.event.request.impl.message.IMessageHandler;
import cn.zl.GB28181.transmit.event.request.impl.message.notify.NotifyMessageHandler;
import cn.zl.GB28181.utils.DateUtils;
import cn.zl.GB28181.utils.SipUtils;
import cn.zl.common.ZLConst;
import cn.zl.config.UserSettingConfig;
import cn.zl.model.Device;
import cn.zl.model.Platform;
import gov.nist.javax.sip.message.SIPRequest;
import jakarta.annotation.Resource;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.sip.InvalidArgumentException;
import javax.sip.RequestEvent;
import javax.sip.SipException;
import javax.sip.message.Response;
import java.text.ParseException;

/**
 * 状态信息(心跳)报送
 */
@Component
public class KeepaliveNotifyMessageHandler extends BaseSIPRequestProcessor implements InitializingBean, IMessageHandler {


    private static final Logger logger = LoggerFactory.getLogger(KeepaliveNotifyMessageHandler.class);
    private static final String cmdType = "Keepalive";

    @Resource
    private NotifyMessageHandler notifyMessageHandler;
    @Resource
    private IDeviceStorage deviceStorage;
    @Resource
    private UserSettingConfig userSettingConfig;
    @Resource(name = "DynamicTaskExecutor")
    private ThreadPoolDynamicTaskExecutor dynamicTask;

    @Override
    public void afterPropertiesSet() throws Exception {
        notifyMessageHandler.addHandler(cmdType, this);
    }

    @Override
    public void handForDevice(RequestEvent evt, Device device, Element element) {
        if (device == null) {
            // 未注册的设备不做处理
            return;
        }
        SIPRequest request = (SIPRequest) evt.getRequest();
        logger.info("[收到心跳] device: {}, callId: {}", device.getDeviceId(), request.getCallIdHeader().getCallId());
        if (userSettingConfig.getGbDeviceOnline() == 0 && !device.isOnLine()) {
            logger.warn("[收到心跳] 设备离线，心跳不进行回复， device: {}, callId: {}", device.getDeviceId(), request.getCallIdHeader().getCallId());
            return;
        }
        // 回复200 OK
        try {
            responseAck(request, Response.OK);
        } catch (SipException | InvalidArgumentException | ParseException e) {
            logger.error("[命令发送失败] 心跳回复: {}", e.getMessage());
        }
        if (!ObjectUtils.isEmpty(device.getKeepaliveTime()) && DateUtils.getDifferenceForNow(device.getKeepaliveTime()) <= 3000L) {
            logger.info("[收到心跳] 心跳发送过于频繁，已忽略 device: {}, callId: {}", device.getDeviceId(), request.getCallIdHeader().getCallId());
            return;
        }

        RemoteAddressInfo remoteAddressInfo = SipUtils.getRemoteAddressFromRequest(request, userSettingConfig.isSipUseSourceIpAsRemoteAddress());
        if (!device.getIp().equalsIgnoreCase(remoteAddressInfo.getIp()) || device.getPort() != remoteAddressInfo.getPort() || !request.getRemoteAddress().getHostAddress().equals(device.getLocalIp())) {
            logger.info("[收到心跳] 设备{}地址变化, 远程地址为: {}:{}", device.getDeviceId(), remoteAddressInfo.getIp(), remoteAddressInfo.getPort());
            device.setPort(remoteAddressInfo.getPort());
            device.setHostAddress(remoteAddressInfo.getIp().concat(":").concat(String.valueOf(remoteAddressInfo.getPort())));
            device.setIp(remoteAddressInfo.getIp());
            device.setLocalIp(request.getRemoteAddress().getHostAddress());
            // 设备地址变化会引起目录订阅任务失效，需要重新添加
            if (device.getSubscribeCycleForCatalog() > 0) {
                deviceStorage.removeCatalogSubscribe(device, result -> {
                    deviceStorage.addCatalogSubscribe(device);
                });
            }
        }
        if (device.getKeepaliveTime() == null) {
            device.setKeepaliveIntervalTime(60);
        } else {
            long lastTime = DateUtils.yyyy_MM_dd_HH_mm_ssToTimestamp(device.getKeepaliveTime());
            if (System.currentTimeMillis() / 1000 - lastTime > 10) {
                device.setKeepaliveIntervalTime(Long.valueOf(System.currentTimeMillis() / 1000 - lastTime).intValue());
            }
        }

        device.setKeepaliveTime(DateUtils.getNow());

        if (device.isOnLine()) {
            deviceStorage.updateDevice(device);
        } else {
            if (userSettingConfig.getGbDeviceOnline() == 1) {
                // 对于已经离线的设备判断他的注册是否已经过期
                device.setOnLine(true);
                device.setRegisterTime(DateUtils.getNow());
                deviceStorage.online(device, null);
            }
        }
        // 刷新过期任务
        String registerExpireTaskKey = ZLConst.REGISTER_EXPIRE_TASK_KEY_PREFIX + device.getDeviceId();
        // 如果三次心跳失败，则设置设备离线
        dynamicTask.startDelay(registerExpireTaskKey, () -> deviceStorage.offline(device.getDeviceId(), "三次心跳失败"), device.getKeepaliveIntervalTime() * 1000 * 3);

    }

    @Override
    public void handForPlatform(RequestEvent evt, Platform parentPlatform, Element element) {
        // 个别平台保活不回复200OK会判定离线
        try {
            responseAck((SIPRequest) evt.getRequest(), Response.OK);
        } catch (SipException | InvalidArgumentException | ParseException e) {
            logger.error("[命令发送失败] 心跳回复: {}", e.getMessage());
        }
    }
}
